<?php namespace Wx\Api;

use Hdphp\Api\Api;

use Wx\Model\Menu as MenuModel;

class Menu extends Api
{
	protected $db;

	public function __construct()
	{
		$this->db = new MenuModel;
		//临时改变配置项的表前缀
		Config::set('database.prefix','wx_');
		// var_dump(Config::get('database.prefix'));
	}

	/**
	 * 获得顶级菜单
	 * autor 梁子亮
	 * 2015年7月23日08:57:16
	 * @return [type] [description]
	 */
	public function getListMenu()
	{
		$menu = Db::table( 'button' )->where('pid',0)->orderBy( 'sort', 'ASC' )->get();
		//把数组转化为二维数组
		if($menu){
            foreach ($menu as $k => $v) {
                $menu[$k]['son'] = Db::select("select * from wx_button where pid = ? order by sort ASC",[$v['id']]);
            }
        }
		// var_dump($menu);die;
		return $menu;
	}

	/**
	 * 获得顶级菜单
	 * autor 梁子亮
	 * 2015年7月23日08:57:16
	 * @return [type] [description]
	 */
	public function push()
	{
		$weixinid = 4;
        $info = Db::table('info')->where('id', $weixinid)->get(['appid','appsecret']);
        $appid = $info[0]['appid'];
        $appsecret = $info[0]['appsecret'];
        Weixin::appID($appid);
        Weixin::appsecret($appsecret);
        $token = Weixin::getAccessToken();
        $data = Db::select("select * from wx_button where pid = 0 and wxid = ? order by create_at ASC",[$weixinid]);
        if($data){
            foreach ($data as $k => $v) {
                $data[$k]['son'] = Db::select("select * from wx_button where pid = ? and wxid = ? order by create_at ASC",[$v['id'],$weixinid]);
            }
        }
        // var_dump($data);die;
        //组成微信需要的数组格式
        $arr = array();
        if($data){
            foreach ($data as $k => $v) {
                $arr[$k]['name'] = $v['name'];
                if($v['type'] == 1){
                    $arr[$k]['type'] = 'view';
                    $arr[$k]['url'] = $v['content'];
                }else{
                    $arr[$k]['type'] = 'click';
                    $arr[$k]['key'] = $v['id'];
                }
                if($v['son']){
                    $arr2 = array();
                    foreach ($v['son'] as $key =>$value ) {
                        $arr2[$key]['name'] = $value['name'];
                        if($value['type'] == 1){
                            $arr2[$key]['type'] = 'view';
                            $arr2[$key]['url'] = $value['content'];
                        }else{
                            $arr2[$key]['type'] = 'click';
                            $arr2[$key]['key'] = $value['id'];
                        }
                    }
                    unset($arr[$k]['type']);
                    unset($arr[$k]['key']);
                    $arr[$k]['sub_button'] = $arr2;
                }

            }
        }
        if(!$arr)
        {
        	$this->error('菜单名称不能为空');
        	return false;
        }else
        {
	        $arr2 = array('button'=>$arr);
	        $final = self::json_encode($arr2);
	        $re = Weixin::createButton($final);
	        var_dump($re);die;
	        return $re;
        }
	}

	//撤销微信菜单
	public function revoke(){

		$weixinid = 4;
        $info = Db::table('info')->where('id', $weixinid)->get(['appid','appsecret']);
        $appid = $info[0]['appid'];
        $appsecret = $info[0]['appsecret'];
        Weixin::appID($appid);
        Weixin::appsecret($appsecret);
        $token = Weixin::getAccessToken();
		$re = Weixin::delButton();
        var_dump($re);die;
		return $re;
    }

    public function http_get($url){
	    $oCurl = curl_init();
	    if(stripos($url,"https://")!==FALSE){
	        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
	        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
	        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
	    }
	    curl_setopt($oCurl, CURLOPT_URL, $url);
	    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
	    $sContent = curl_exec($oCurl);
	    $aStatus = curl_getinfo($oCurl);
	    curl_close($oCurl);
	    if(intval($aStatus["http_code"])==200){
	        return $sContent;
	    }else{
	        return false;
	    }
	}


	public function http_post($url,$param,$post_file=false){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }


    static function json_encode($arr) {
        $parts = array ();
        $is_list = false;
        //Find out if the given array is a numerical array
        $keys = array_keys ( $arr );
        $max_length = count ( $arr ) - 1;
        if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
            $is_list = true;
            for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
                if ($i != $keys [$i]) { //A key fails at position check.
                    $is_list = false; //It is an associative array.
                    break;
                }
            }
        }
        foreach ( $arr as $key => $value ) {
            if (is_array ( $value )) { //Custom handling for arrays
                if ($is_list)
                    $parts [] = self::json_encode ( $value ); /* :RECURSION: */
                else
                    $parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */
            } else {
                $str = '';
                if (! $is_list)
                    $str = '"' . $key . '":';
                //Custom handling for multiple data types
                if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
                    $str .= $value; //Numbers
                elseif ($value === false)
                $str .= 'false'; //The booleans
                elseif ($value === true)
                $str .= 'true';
                else
                    $str .= '"' . addslashes ( $value ) . '"'; //All other things
                // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
                $parts [] = $str;
            }
        }
        $json = implode ( ',', $parts );
        if ($is_list)
            return '[' . $json . ']'; //Return numerical JSON
        return '{' . $json . '}'; //Return associative JSON
    }


	/**
	 * 删除菜单
	 *
	 * @param  [type] $id [description]
	 *
	 * @return [type]     [description]
	 */
	public function destroy( $id )
	{
		//是否有子菜单
		if ( Db::table( 'button' )->where( 'pid', $id )->first() )
		{
			$this->error = '删除主菜单会连同其下的子菜单一并删除,确定操作 ？';

			return false;
		}else
		{
			//查出有多少个与这个id处于同一pid的菜单（用于判断如果是5个的话，ajax删除后在html那边要显示添加子菜单这一行...）
			$pid = Db::table("button")->where('id',$id)->pluck('pid');
			// var_dump($pid);die;
			$count = Db::table("button")->where('pid',$pid)->count('id');
			$re = $this->db->delete($id);
			$lastid = '';
			if($count == 5){
				$lastid = Db::table("button")->where('pid',$pid)->orderBy('sort','DESC')->pluck('id');
			}
				$data = array($re,$lastid,$pid);
				return $data;
		}

	}


	/**
	 * 获得所有菜单
	 * autor 梁子亮
	 * 2015年7月23日15:45:08
	 * @return [type] [description]
	 */
	public function del_all($id)
	{
		return Db::update('DELETE FROM wx_button WHERE id=? OR pid =?',[$id,$id]);

	}


	//更新菜单
	public function update($id)
	{
		if(!trim($_POST['val']))
		{
			$this->error = '内容不能为空!';
			return false;
		}
		else
		{
			$data = array(
				'id' => $_POST['id'],
				$_POST['name'] => trim($_POST['val'])
			);
			return $this->db->save($data);
		}
	}

	//新增菜单
	public function store()
	{
		if(!$_POST['name'])
		{
			$this->error = '菜单名称不能为空!';
			return false;
		}
		else
		{
			$pid = $_POST['pid'];
			// $newpid = Db::table("button")->where('id',$pid)->pluck('pid');
			// var_dump($pid);die;
			//排序,先找出当前pid有多少个
			$count = Db::table("button")->where('pid',$pid)->count('id');
			//再找出当前pid最大的sort，然后判断是主菜单就加上1，否则是子菜单就加上0.1
			if(!$pid)
			{
				$newsort = Db::table("button")->where('pid',0)->max('sort') + 1;
			}
			elseif(!$count)
			{
				$newsort = Db::table("button")->where('id',$pid)->max('sort') + 0.1;
			}
			else
			{
				$newsort = Db::table("button")->where('pid',$pid)->max('sort') + 0.1;
			}
			// var_dump($newsort);die;
			$data = array(
				'name' => $_POST['name'],
				'type' => $_POST['type'],
				'content' => $_POST['content'],
				'pid' => $pid,
				'create_at' => time(),
				'sort' => $newsort
				// 'wxid' => $_SESSION['wxid'],
			);
			// var_dump($data);die;
			$d = Db::insert('INSERT INTO wx_button (name,type,content,pid,create_at,sort) VALUES(?,?,?,?,?,?)',[$_POST['name'],$_POST['type'],$_POST['content'],$pid,time(),$newsort]);
			if ( $d )
			{
				return true;
			}
		}
	}
}